﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using KL.UFrame.Core.Exception;
using KL.UFrame.Data.Entities;

namespace KL.UFrame.Data.Business.Account
{
    /// <summary>
    /// oauth管理接口
    /// </summary>
    public class OAuthBusiness:BusinessBase,IOAuthBusiness
    {
        /// <summary>
        /// 添加一个oauth客户端
        /// </summary>
        /// <param name="client"></param>
        /// <returns>客户端Id</returns>
        public async Task<string> CreateClientAsync(OAuthClient client)
        {
            client.ClientId = Guid.NewGuid().ToString("N");
            client.ClientSecret= Guid.NewGuid().ToString("N");
            client.CreateTime = DateTime.Now;
            Db.OAuthClients.Add(client);
            if (await Db.SaveChangesAsync() > 0)
            {
                return client.ClientId;
            }
            throw new ResultException(-500,"新增客户端失败");
        }

        /// <summary>
        /// 通过客户端Id和Secret查找
        /// </summary>
        /// <param name="id"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public async Task<OAuthClient> FindAsync(string id, string secret)
        {
            var client = await Db.OAuthClients.FirstOrDefaultAsync(a => a.ClientId == id && a.ClientSecret == secret);
            return client;
        }
    }
}